package org.example.interceptor;

import org.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取令牌
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //1.非空校验
            if(token == null) {
                throw new Exception("token 数据异常！");
            }
            //2.从 redis 上获取用户信息(用来打印日志)
            String username = (String) redisTemplate.opsForValue().get(token);
            if(username == null || username.isEmpty()) {
                throw new Exception("token 数据异常！");
            }
            Map<String,Object> claims = JwtUtil.parseToken(token);
            //没有异常就放行
            return true;
        } catch (Exception e) {
            //未登录,不放行
            response.setStatus(401);
//            String msg = Result.noLogin("清先完成登录操作！").toString();
//            response.getWriter().println(msg);
            return false;
        }
 
    }
}